package org.donhuan.rms.ui.actions;

import org.donhuan.rms.ui.listeners.LoginListener;
import org.donhuan.rms.ui.model.Session;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;

public class LoginAction extends Job {
	private LoginListener listener;
	private Session session = Session.getInstance();

	public LoginAction(String name) {
		super(name);
	}

	public void addLoginListener(LoginListener listener) {
		this.listener = listener;
	}

	public void fireLoginComplete() {
		listener.loginComplete();
	}

	public void fireLoginStarted() {
		listener.loginStarted();
	}

	public void fireLoginError(String message) {
		listener.loginError(message);
	}

	public void fireLoginCancled() {
		listener.loginCanceled();
	}

	@Override
	protected IStatus run(IProgressMonitor monitor) {
		login();
		return Status.OK_STATUS;
	}

	private boolean login() {
		fireLoginStarted();
		if (session.getConnection() == null) {
			fireLoginError(Session.CONNECT_FAILED);
		} else {
		
			if (session.getPerson() == null)
				fireLoginError(Session.LOGIN_FAILED);
			else {
				session.setAuthenticated(true);
				fireLoginComplete();
				MessageDialog.openConfirm(null, "Logining...", "Welcome "
						+ session.getPerson().getNickName() + " come back!");
			}
		}
		return session.isAuthenticated();
	}

}
